<?php
namespace app\common\controller;
use think\Controller;
use think\Db;
class Vehicle extends Controller
{
    // 更新车辆利润
    public function updateProfit($vehicleId)
    {
        # 车辆开支 $income
        $map = [
            'vehicle_id' => $vehicleId,
            'status' => 20
        ];
        $rows = db('VehicleIncomeExpense')->where($map)->select();
        $income = 0;
        foreach ($rows as $v) {
            $income += $v['io_type'] == '收入' ? $v['amount'] : $v['amount'] * -1;
        }

        # 成本cost 车辆收购价
        $vehicle = db('Vehicle')->where(['id'=>$vehicleId])->find(); 
        $cost = $vehicle['buy_price'] + $vehicle['buy_agent_fee'] + $vehicle['buy_other_fee'];

        # 利润 = 车辆收入 - 车辆购买成本
        $profit = $income - $cost;

        db('Vehicle')->where(['id'=>$vehicleId])->update(['profit'=>$profit]);
    }

}
